/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.songlanyun.modules.user.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.songlanyun.common.enums.SysConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.Constant;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;

import com.songlanyun.modules.user.dao.SysRoleDao;
import com.songlanyun.modules.user.entity.SysRoleEntity;
import com.songlanyun.modules.user.entity.SysUserEntity;
import com.songlanyun.modules.user.exception.UserException;
import com.songlanyun.modules.user.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.management.relation.Role;
import java.util.*;


/**
 * 角色
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysUserService sysUserService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String roleName = MapUtil.getStr(params, "roleName");
        String createUserId = MapUtil.getStr(params, "createUserId");

        IPage<SysRoleEntity> page = this.page(
                new Query<SysRoleEntity>().getPage(params),
                new LambdaQueryWrapper<SysRoleEntity>()
                        .eq(StringUtils.isNotBlank(createUserId), SysRoleEntity::getCreateUserId, createUserId)
                        .like(StringUtils.isNotBlank(roleName), SysRoleEntity::getRoleName, roleName)
        );


        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRole(SysRoleEntity role) {
        role.setCreateTime(new Date());
        this.save(role);

        //保存角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysRoleEntity role) {
        this.updateById(role);

        //更新角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] roleIds) {
        //系统角色不能删除
        if (this.baseMapper.countTypesByIds(roleIds)) {
            throw new RRException(UserException.SYS_ROLE_NOT_DEL);
        }

        //如果该角色已分配给用户，则不能删除
        List<String> list = this.baseMapper.countUsernameByIds(roleIds);
        if (list != null && list.size() > 0) {
            throw new RRException(String.format("该角色已被分配，分配的用户名有：%s", list.toString()));
        }

        //删除角色
        this.removeByIds(Arrays.asList(roleIds));

        //删除角色与菜单关联
        sysRoleMenuService.deleteBatch(roleIds);

        //删除角色与用户关联
        sysUserRoleService.deleteBatch(roleIds);
    }

    @Override
    public Long getRoleIdByAdmin(Integer roleType) {

        SysRoleEntity sysRoleEntity = this.baseMapper.selectOne(
                new LambdaQueryWrapper<SysRoleEntity>()
                        .eq(SysRoleEntity::getCreateUserId, Constant.SUPER_ADMIN)
                        .eq(SysRoleEntity::getRoleType, roleType)
                        .last("limit 1")
        );
        if (sysRoleEntity == null) {
            throw new RRException(UserException.ADMIN_ERROR);
        }
        return sysRoleEntity.getRoleId();
    }

    @Override
    public void saveUserRole(SysUserEntity user, Integer roleType) {
        Long roleId = this.getRoleIdByAdmin(roleType);
        List<Long> roleIdList = new ArrayList<>();
        roleIdList.add(roleId);
        user.setRoleIdList(roleIdList);//设置平台商家管理员的角色
        sysUserService.saveUser(user);

    }

    @Override
    public List<Long> getAdminUserRole() {
        List<SysRoleEntity> list = this.baseMapper.selectList(
                new LambdaQueryWrapper<SysRoleEntity>()
                        .eq(SysRoleEntity::getCreateUserId, Constant.SUPER_ADMIN)
                        .gt(SysRoleEntity::getRoleType, 0)
        );
        List<Long> roleIds = new ArrayList<>();
        for (SysRoleEntity r : list) {
            roleIds.add(r.getRoleId());
        }
        return roleIds;
    }

    @Override
    public String getRoleNameByUserId(Long userId) {
        return this.baseMapper.getRoleNameByUserId(userId);
    }

    @Override
    public Integer getRoleTypeByUserId(Long userId) {
        return this.baseMapper.getRoleTypeByUserId(userId);
    }


}
